package es.udc.emarketapp.emarket.model.shipping.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.GeneralOperations;
import es.udc.emarketapp.emarket.model.shipping.vo.ShippingVO;


// An implementation of <code>SQLProductDAO</code> for databases providing
// counter columns with JDBC 3 drivers.
 

public class MySQLShippingDAO extends AbstractSQLShippingDAO {

    public ShippingVO create(Connection connection, ShippingVO shippingVO)
        throws InternalErrorException {
        
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
    
        try {
                
            // Create "preparedStatement". 
            String queryString = "INSERT INTO envia" +
                "(id_vendedor, id_pais, peso, precio)" +
                "VALUES (?, ?, ?, ?)";
        
            preparedStatement = connection.prepareStatement(queryString);    
            
            // Fill "preparedStatement". 
            int i = 1;
            preparedStatement.setString(i++, shippingVO.getIdVendedor());
            preparedStatement.setString(i++, shippingVO.getIdPais());
            preparedStatement.setDouble(i++, shippingVO.getPeso());
            preparedStatement.setDouble(i++, shippingVO.getPrecio());
      
                        
            // Execute query.
            int insertedRows = preparedStatement.executeUpdate();
        
            if (insertedRows == 0) {
                throw new SQLException("No se pudo insertar la fila a la tabla" +
                    " 'Envia'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Fila duplicada en la tabla 'Envia'");
            }
            
          
            // Return the value object. 
            return shippingVO;
            
        
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }
        
    }

}